import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gridItems: [
      { id:1,value: 1 },
      { id:2,value: 2 },
      { id:3,value: 3 },
      { id:0,value: 0 },
      { id:4,value: 4 },
      { id:5,value: 5 },
      { id:6,value: 6 },
      { id:7,value: 7 },
      { id:8,value: 8 },
      { id:9,value: 9 },
      { id:'delete',value: '删除' },
    ],
    value:'',
    tabNum:null,
    questionIndex:0,//当前题型索引
    topicContent:[],//当前题型所有题目
    timeStr: 0,//页面倒计时
    totalCount: 0,//题目数量
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    imageUrl: '', //图片
    questionAnswer:null,//答案
    countdownInterval: null, // 存储 interval ID
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();

    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      totalCount:count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },
  getCurrentTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {topicContent,currentIndex,totalCount} = this.data;
    // 缓存下一题图片
    let newIndex = currentIndex + 1;
    if(newIndex < totalCount){
      util.preLoadImg(questionIndex,newIndex)
    }
    const preImgs = wx.getStorageSync('preImgs')||[];

    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    const questionContent = JSON.parse(currentTopic.answerSheet).content;// 大图数据
    const questionCountdown = JSON.parse(currentTopic.answerSheet).residenceTime;
    const timeStr = parseInt(questionCountdown, 10) / 1000;//停留时长
    const questionImgSrc = questionContent.match(/<img[^>]+src="([^">]+)"/);
    // const imageUrl = util.base_url + questionImgSrc[1];// 拼接图片
    let imageUrl = '';
    if (questionImgSrc && questionImgSrc[1]) {
      let imgSrc = questionImgSrc[1];
      
      // 判断是否已经包含完整的 URL（http 或 https）
      if (imgSrc.startsWith('http')) {
        imageUrl = imgSrc;
      } else {
        imageUrl = util.base_url + imgSrc;
      }
    }
    // 替换缓存图片
    const isIos =  util.checkPlatform()
    if(isIos){
      imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,jpg'
    }else{
      imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,webp'
    }
    
    const numberArray = currentTopic.optionList;//选项
    const questionAnswer = currentTopic.questionAnswer;//答案
    const descArray = JSON.parse(currentTopic.describe); // 得到标题数组
    const title = descArray[0].content;// 标题数据
    this.setData({
      currentTopic,
      imageUrl,
      numberArray,
      questionAnswer,
      title,
      timeStr,
      tabNum: null,
      value:'',
      // 记录题目开始时间
      questionStartTime: new Date().getTime()
    });
    this.startCountdown(); // 添加倒计时
  },
  // 启动倒计时
  startCountdown() {
    const { countdownInterval } = this.data;
    // 清除已有倒计时
    if (countdownInterval) {
      clearInterval(countdownInterval);
    }

    const interval = setInterval(() => {
      this.setData({
        timeStr: this.data.timeStr - 1
      });

      if (this.data.timeStr <= 0) {
        this.handleTimeout(); // 处理超时逻辑
        clearInterval(interval);
      }
    }, 1000);

    this.setData({ countdownInterval: interval });
  },   
  // 超时事件
  handleTimeout() {
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(true);
    this.setData({
      answerRecords: newAnswerRecords
    })

    setTimeout(() => {
      let {currentIndex,totalCount} = this.data;
      // 无论对错都增加总次数
      let countNum = currentIndex + 1;
      this.setData({
        tabNum: null,
        currentIndex: countNum,
        value:''
      })
      if (countNum >= totalCount) {
          //跳转下一题
          let questionNumber = this.data.questionIndex + 1;
          const prevInfo = wx.getStorageSync('questionInfo') || {};
          wx.setStorageSync('questionInfo', {
            ...prevInfo,
            questionNumber
          });
          util.navigateByDesc(questionNumber);
      } else {
        this.getCurrentTopicData()
      }
    }, 1000);
  },
  onTap(e) {
    const key = e.currentTarget.dataset.value;
    let currentValue = this.data.value;
    if (key === 'delete') {
      const newValue = String(currentValue).slice(0, -1);
      this.setData({
        value: newValue
      });
    } else {
      this.setData({
        value: key
      });
    }
    this.setData({
      tabNum: key
    })
  },
  onSubmit(){
    let {totalCount,currentIndex} = this.data;
    const value = this.data.value.toString();
    if (!value) return;

    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value);

    let countNum = currentIndex + 1;
    this.setData({
      tabNum: null,
      currentIndex: countNum,
      value:'',
      answerRecords: newAnswerRecords
    })
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    if (countNum >= totalCount) {
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);//跳转下一题
    } else {
      // 继续下一题
      this.getCurrentTopicData();
    }
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '') {
    const {currentIndex, questionStartTime, topicContent, questionAnswer} = this.data;
    
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);
    
    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];
    
    // 判断是否正确（超时视为错误）
    let isRight = 0;
    let option = '';
    
    if (!isTimeout) {
      option = userOption;
      isRight = (userOption === questionAnswer) ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option.toString(),
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: currentTopic.questionAnswer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },
  onUnload() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
  }
})